<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./bootstrap-3.3.5-dist/css/bootstrap.min.css">
  <title>Document</title>
  <style>
    th,td{
      padding: 10px 20px;
      text-align: center;
    }
    #pre,#next{
      padding: 10px;
      background-color: pink;
      cursor: pointer;
    }
    #pre,#next,#pages{
      float: left;
    }
    #pages div{
      float: left;
      padding: 10px;
      margin: 0 10px;
      background-color: pink;
      cursor: pointer;
    }
    #xiugaikuang{
      position: absolute;
      top: 100px;
      left: 50%;
      padding: 20px;
      border: 1px solid red;
      background-color: gray;
      display: none;
    }
  </style>
</head>
<body>
  <form class="form-inline">
    <div class="form-group">
      <input type="text" class="form-control" id="stuNames" placeholder="请输入学生姓名">
    </div>
    <button type="submit" class="btn btn-info">搜索</button>
    <button type="reset" class="btn btn-info">重置</button>
    <button type="button" class="btn btn-success">添加学生</button>
  </form>

  <div id="mainDiv">
    <table class="table table-bordered table-hover">
      <thead>
        <tr>
          <th>学号</th>
          <th>姓名</th>
          <th>帐号</th>
          <th>学生所属宿舍</th>
          <th>宿舍水电费余额(元)</th>
          <th>宿舍状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
       
      </tbody>
    </table>
    <!-- <div id="xiugaikuang">
      <form action="">
        <label>学号：<input type="text" id="stuId" disabled></label>
        <br>
        <label>学生姓名：<input type="text" id="stuName"></label>
        <br>
        <label>学生性别：<input type="text" id="stuSex"></label>
        <br>
        <label>学生年龄：<input type="text" id="stuAge"></label>
        <br>
        <button type="button" id="querenxiugai">确定修改</button>
        <button type="button" id="quxiao">取消</button>
      </form>
    </div> -->
    <!-- 修改Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">修改学生信息</h4>
          </div>
          <div class="modal-body">
            <!-- 表单 -->
            <form class="form-horizontal">
              <div class="form-group">
                <label for="stuId" class="col-sm-2 control-label">学号</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="stuId" disabled>
                </div>
              </div>
              <div class="form-group">
                <label for="stuName" class="col-sm-2 control-label">姓名</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="stuName">
                </div>
              </div>
              <div class="form-group">
                <label for="stuUserId" class="col-sm-2 control-label">账号</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="stuUserId">
                </div>
              </div>
              <div class="form-group">
                <label for="stuPas" class="col-sm-2 control-label">密码</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="stuPas">
                </div>
              </div>
              <div class="form-group">
                <label for="dormId" class="col-sm-2 control-label">所属宿舍</label>
                <div class="col-sm-8">
                  <select name="form-control" id="dormId">
                    <option value="59">1001</option>
                    <option value="2">1002</option>
                    <option value="4">1004</option>
                    <option value="5">1005</option>
                    <option value="6">1006</option>
                    <option value="51">1007</option>
                    <option value="61">1008</option>
                  </select>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" onclick="updateStu()">确定</button>
          </div>
        </div>
      </div>
    </div>

    <div>
      <div id="pre">上一页</div>
      <div id="pages">
        <!-- <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div> -->
      </div>
      <div id="next">下一页</div>
    </div>
  </div>

  <script src="./jquery-1.11.3.js"></script>
  <script src="./bootstrap-3.3.5-dist/js/jquery-1.11.3.js"></script>
  <script src="./bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
  <script src="./utlis.js"></script>
  <script>
    //模拟假数据
    let student = [];

    let nowPage = 1;
    let maxPage;

    window.onload = function(){
      //获取本地存储的isLogin
      // let isLogin1 = localStorage.getItem('isLlogin');
      // let isLogin = getStorage('isLlogin');
      // let stu = sessionStorage.getItem('arrStu');
      
      // console.log(typeof JSON.parse(stu));
      // console.log(isLogin);
//--------!!isLogin---------
//--------!isLogin--->!"fasle"
//------------------->!true--->false
//-----------------------------!false-->true
      // if(isLogin){
        getStudent();
      // }else{
      //   location.href = 'day18-2.html'
      // }
    }
    //获取学生列表
    function getStudent(){
      //发送请求，获取学生数据
      $.ajax({
        url:'http://47.109.16.231:3000/student/getstudent',
        type:'get',
        success:function(res){
          console.log(res);
          student = res.data;
          //---------初始化
          showPage(student);
        }
      })
    }

    //动态渲染表格
    function showTbody(start,end,tbodyData){
      $('#mainDiv>table>tbody').html('');
      //目的 --->往tbody中添加tr和td
      for(let i = start;i <= end;i++){
        //判断是否是最后一页
        if (tbodyData.length > i) {
          $('#mainDiv>table>tbody').append(`
            <tr>
              <td>${tbodyData[i].stuId}</td>
              <td>${tbodyData[i].stuName}</td>
              <td>${tbodyData[i].stuUserId}</td>
              <td>${tbodyData[i].dormId}</td>
              <td>${tbodyData[i].balance}</td>
              <td>${tbodyData[i].type == 1 ? '正常':'催款中'}</td>
              <td>
                <button class="xiugai btn btn-primary" data-id=${tbodyData[i].id} data-toggle="modal" data-target="#myModal">修改</button>
                <button class="btn btn-default">删除</button>
              </td>
            </tr>
          `)
        }
      }
    }
    //渲染页码
    function showPage(stuData){
      //知道有多少页---一页展示5条数据
      let pageNum = Math.ceil(student.length/5);
      maxPage = pageNum;
      for(let i = 0; i < pageNum;i++){
        //往pages中添加页码
        $('#pages').append(`<div>${i + 1}</div>`)
      }
      //渲染tbody
      showTbody(0,4,stuData)
    }

  //-------------------------------------------------
    $('#next').click(function(){
      //渲染当前页的下一页的数据
      //知道当前页-----下一页 当前页++
      let page;
      nowPage < maxPage ? page = nowPage + 1:page = nowPage;
      let start = (page - 1)*5;
      let end = page*5 - 1;
      showTbody(start,end,student);
      nowPage = page;
    })

    $('#pre').click(function(){
      //渲染当前页的上一页的数据
      //知道当前页-----上一页 当前页--
      let page;
      nowPage > 1 ? page = nowPage - 1:page = nowPage;
      let start = (page - 1)*5;
      let end = page*5 - 1;
      showTbody(start,end,student);
      nowPage = page;
    })

//--------页码翻页：事件委托----------
    $('#pages').on('click','div',function(){
      //渲染对应页号码的数据
      //1.1获取当前点击的页码
      let page =  parseInt($(this).text());
      //1.2根据当前号码计算起始结束的位置
      let start = (page - 1)*5;
      let end = page*5 - 1;
      //1.3渲染表格
      showTbody(start,end,student);
      //1.4更新nowpage
      nowPage = page;
    })
//-------------------修改
    let stuUpdate = {};
    $('tbody').on('click','.xiugai',function(){
      //1.修改框显示
      $('#xiugaikuang').css({display:'block'});
      //2.将当前的这条修改信息展示在我的div上（回显）
      let stuId = parseInt($(this).attr('data-id')); 
      stuUpdate.id = stuId;
      //筛选器
      let mydata = student.filter(item => {
        return item.id === stuId
      })
      console.log(mydata);
      $('#stuId').val(mydata[0].stuId)
      $('#stuName').val(mydata[0].stuName)
      $('#stuUserId').val(mydata[0].stuUserId)
      $('#stuPas').val(mydata[0].stuPas)
      $('#dormId').val(mydata[0].stuDormId)
    })

    //修改功能
    function updateStu(){
      // console.log(stuUpdate);
      //1.获取表单数据
      let stuId = $('#stuId').val();
      let stuName = $('#stuName').val();
      let stuUserId = $('#stuUserId').val();
      let stuPas = $('#stuPas').val();
      let stuDormId = $('#dormId').val();
      // stuUpdate.stuId = stuId;
      stuUpdate = {...stuUpdate,...{stuName,stuPas,stuUserId,stuDormId}};
      console.log(stuUpdate);
      // 2.发送请求，将数据给后台
      $.ajax({
        url:'http://47.109.16.231:3000/student/updatestudent',
        type:'post',
        data:stuUpdate,
        success:function(res){
          console.log(res);
          getStudent();
          $('#myModal').modal('hide')
        }
      })
    }
    $('#querenxiugai').click(function(){
      //获取表单里的数据
      let obj ={
        id: parseInt($('#stuId').val()),
        name: $('#stuName').val(),
        sex: $('#stuSex').val(),
        age:$('#stuAge').val()
      }
      //讲这些数据和student数据中的对应那条互换（替换）
      for(let i = 0;i<student.length;i++){
        if (student[i].id === obj.id) {
          student.splice(i,1,obj);
        }
      }
      //清空表单，关闭div
      $('#stuId').val('')
      $('#stuName').val('')
      $('#stuSex').val('')
      $('#stuAge').val('')
      //属性表格
      let start = (nowPage - 1)*5;
      let end = nowPage*5 - 1;
      showTbody(start,end,student);
      $('#xiugaikuang').css({display:'none'})
    })
    $('#quxiao').click(function(){
      $('#stuId').val('')
      $('#stuName').val('')
      $('#stuSex').val('')
      $('#stuAge').val('')
      $('#xiugaikuang').css({display:'none'})
    })
  </script>
</body>
</html>